package cn.yshujia.service.impl;

import cn.yshujia.domain.dto.PageDTO;
import cn.yshujia.domain.entity.Website;
import cn.yshujia.domain.vo.PageVO;
import cn.yshujia.domain.vo.WebsiteVO;
import cn.yshujia.mapper.WebsiteMapper;
import cn.yshujia.repository.WebsiteRepository;
import cn.yshujia.utils.IDUtils;
import cn.yshujia.utils.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author YShuJia
 * @create 2024/4/23
 * @description 服务层
 */

@Service
public class WebsiteServiceImpl extends ServiceImpl<WebsiteMapper, Website> implements IService<Website> {
	
	@Resource
	private WebsiteMapper mapper;
	
	@Resource
	private WebsiteRepository repository;
	
	public PageVO<WebsiteVO> page(PageDTO dto) {
		return repository.pageByIsRecommend(dto);
	}
	
	public PageVO<WebsiteVO> adminPage(PageDTO dto) {
		QueryWrapper<Website> wrapper = PageUtils.createAlbumWrapper(dto);
		IPage<Website> page = mapper.selectPage(new Page<>(dto.getCurrent(), dto.getSize()), wrapper);
		// 创建VO集合
		if (!ObjectUtils.isEmpty(page) && !ObjectUtils.isEmpty(page.getRecords())) {
			return PageUtils.getPage(dto, repository.createVOList(page.getRecords()), page.getTotal());
		}
		return new PageVO<>();
	}
	
	@Transactional (rollbackFor = {Exception.class})
	public Boolean insert(Website dto) {
		dto.setId(IDUtils.getId());
		dto.setLabelId(40000001L);
		int r = mapper.insert(dto);
		// 插入成功，添加到缓存中
		if (r > 0) {
			repository.del();
		}
		return r > 0;
	}
	
	@Transactional (rollbackFor = {Exception.class})
	public Boolean update(Website dto) {
		int r = mapper.updateById(dto);
		// 更新成功，删除缓存
		if (r > 0) {
			repository.del();
		}
		return r > 0;
	}
	
	@Transactional (rollbackFor = {Exception.class})
	public Boolean remove(List<Long> ids) {
		int r = mapper.deleteByIds(ids);
		// 删除成功，删除缓存
		if (r > 0) {
			repository.del();
		}
		return r > 0;
	}
}